package com.dissertation.service.impl;

import com.dissertation.service.ITagCountService;
import com.mongodb.Mongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class BasicTagCountImpl implements ITagCountService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Value( "${tag.threshold}" )
    int threshold;

    @Override
    public int updateCount( List<String> uniqueNames, int num ) {
        Criteria criteria = new Criteria();
        or( uniqueNames, criteria );
        Query query = Query.query( criteria );
        Update update = new Update().inc( "count", num );
        return mongoTemplate.updateMulti( query, update, "tag" ).getN();
    }

    private void or( List<String> uniqueNames, Criteria criteria ) {
        if ( uniqueNames != null ) {
            int size = uniqueNames.size();
            Criteria[] criteriaArray = new Criteria[size];
            for ( int i = 0; i < size; i++ ) {
                criteriaArray[i] = Criteria.where( "uniqueName" ).is( uniqueNames.get( i ) );
            }
            criteria.orOperator( criteriaArray );
        }
    }

    @Override
    public int updateStatus( List<String> uniqueNames ) {
        Criteria criteria = Criteria.where( "count" ).gte( threshold ).and( "status" ).is( "SELF" );
        or( uniqueNames, criteria );
        Query query = Query.query( criteria );
        Update update = Update.update( "status", "COMMON" );
        return mongoTemplate.updateMulti( query, update, "tag" ).getN();
    }


}
